﻿using System;
using System.Windows.Threading;

namespace Utils
{
	public class UiDispatcher
	{
		private Dispatcher _dispatcher;

		public void Invoke(Action del)
		{
			AssertIsInitialized();

			if (_dispatcher.CheckAccess())
				del();
			else
				_dispatcher.Invoke(del);
		}

		public void BeginInvoke(Action del)
		{
			AssertIsInitialized();

			if (_dispatcher.CheckAccess())
				del();
			else
				_dispatcher.BeginInvoke(del);
		}

		public void BeginInvokeIfInitialized(Action del)
		{
			if (_dispatcher != null)
				BeginInvoke(del);
		}

		private void AssertIsInitialized()
		{
			if (_dispatcher == null)
				throw new Exception("UiDispatcher was not initialized; Dispatcher is missing.");
		}

		public void Start(Dispatcher dispatcher)
		{
			if (_dispatcher != null)
				throw new Exception("UiDispatcher: Dispatcher was already started.");

			_dispatcher = dispatcher;
		}
	}
}
